package com.cn.load.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		ServletInputStream is = request.getInputStream();
		
		PrintStream out = System.out;
		
		byte[] buffer = new byte[1024];
		
		int len = -1;
		
		while((len = is.read(buffer))!=-1){
			out.write(buffer,0,len);
			out.flush();
		}
		
		is.close();
		out.close();
		
		
		
		/*
		//创建一个DiskFileItemFactory
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//创建ServletFileUpload类
		ServletFileUpload upload=new ServletFileUpload(factory);
		if(upload.isMultipartContent(request)){
			//解析所有上传数据
			List<FileItem> items = null;
			try {
				 items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(items!=null){
				for(FileItem f:items){
					if(f.isFormField()){
						System.out.println("组件名字:"+f.getFieldName());
						System.out.println("上传文件的名字:"+f.getName());
						System.out.println("非上传组件的名字:"+f.getString());
						InputStream is = f.getInputStream();
						FileOutputStream fos = new FileOutputStream("E:\\chuanzhi\\workspace\\"+f.getName());
						IOUtils.copy(is, fos);
					}
				}
			}
		}*/
		
	}
	

}
